$(function() {
    let layer = layui.layer
    let form = layui.form
    initCate()

    function initCate() {
        $.ajax({
            method: 'get',
            url: '/my/cate/list',
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('获取文章分类列表失败！')
                }
                let htmlStr = template('tpl_cate', res)
                $('tbody').html(htmlStr)
            }
        })
    }
    let index = null
    $('#addCate').on('click', function() {
        index = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#dialog-add').html()
        });
    })
    $('body').on('submit', '#form_addCate', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'post',
            url: '/my/cate/add',
            data: $(this).serialize(),
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('新增分类失败！')
                }
                layer.msg('新增分类成功！')
                initCate()
                layer.close(index)

            }
        })
    })
    $('tbody').on('click', '.btn_edit', function() {
        index = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#dialog-edit').html()
        });
        let id = $(this).attr('data-id')
        $.ajax({
            method: 'get',
            url: '/my/cate/info?id=' + id,
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('获取分类失败！')
                }
                form.val('form_editCate', res.data)
            }
        })

    })
    $('body').on('submit', '#form_editCate', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'put',
            url: '/my/cate/info',
            data: $(this).serialize(),
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('修改分类失败！')
                }
                layer.msg('修改分类成功！')
                initCate()
                layer.close(index)

            }
        })
    })
    $('tbody').on('click', '.btn_del', function() {
        let id = $(this).attr('data-id')
        layer.confirm('确认是否删除?', { icon: 3, title: '提示' }, function(index) {

            $.ajax({
                method: 'delete',
                url: '/my/cate/del?id=' + id,
                success: function(res) {
                    if (res.code !== 0) {
                        return layer.msg('删除分类失败！')
                    }
                    layer.msg('删除分类成功！')
                    initCate()
                }
            })
            layer.close(index);
        });
    })

})